package com.shop.cereshop.app.controller.wallet;

import com.shop.cereshop.app.service.wallet.RechargeService;
import com.shop.cereshop.app.param.wallet.RechargeVO;
import com.shop.cereshop.app.param.wallet.RechargeResponseVO;
import com.shop.cereshop.commons.domain.wallet.Recharge;
import com.shop.cereshop.commons.result.Result;
import com.shop.cereshop.app.service.buyer.CereBuyerUserService;
import com.shop.cereshop.commons.domain.buyer.CereBuyerUser;
import com.shop.cereshop.commons.utils.EmptyUtils;
import com.shop.cereshop.commons.constant.CoReturnFormat;
import cn.hutool.core.bean.BeanUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 充值控制器
 * @author wang.yao
 * @date 2025-08-26
 */
@Slf4j
@RestController
@RequestMapping("/recharge")
@Api(value = "Recharge", tags = "钱包充值")
public class RechargeController {

    @Autowired
    private RechargeService rechargeService;

    @Autowired
    private CereBuyerUserService cereBuyerUserService;

    @ApiOperation("创建充值订单")
    @PostMapping("/create")
    public Result<RechargeResponseVO> createRechargeOrder(@Valid @RequestBody RechargeVO rechargeVO, HttpServletRequest request) {
        try {
            //获取当前登录账户
            CereBuyerUser user = (CereBuyerUser) request.getAttribute("user");
            if (BeanUtil.isEmpty(user)) {
                return new Result(CoReturnFormat.USER_NOT_LOGIN);
            }
            
            // 设置用户ID
            rechargeVO.setBuyerUserId(user.getBuyerUserId());
            
            RechargeResponseVO responseVO = rechargeService.createRechargeOrder(rechargeVO);
            return new Result(responseVO, CoReturnFormat.SUCCESS);
        } catch (Exception e) {
            log.error("创建充值订单失败，金额：{}", rechargeVO.getAmount(), e);
            return new Result(CoReturnFormat.RECHARGE_CREATE_FAIL);
        }
    }

    @ApiOperation("查询充值记录")
    @GetMapping("/list")
    public Result<List<Recharge>> getRechargeList(@RequestParam(defaultValue = "1") Integer page,
                                                 @RequestParam(defaultValue = "10") Integer size,
                                                 HttpServletRequest request) {
        try {
            //获取当前登录账户
            CereBuyerUser user = (CereBuyerUser) request.getAttribute("user");
            if (BeanUtil.isEmpty(user)) {
                return new Result(CoReturnFormat.USER_NOT_LOGIN);
            }
            
            List<Recharge> rechargeList = rechargeService.getRechargeList(user.getBuyerUserId(), page, size);
            return new Result(rechargeList, CoReturnFormat.SUCCESS);
        } catch (Exception e) {
            log.error("查询充值记录失败", e);
            return new Result(CoReturnFormat.RECHARGE_LIST_FAIL);
        }
    }

    @ApiOperation("查询充值详情")
    @GetMapping("/detail")
    public Result<Recharge> getRechargeDetail(@RequestParam String rechargeNo) {
        try {
            Recharge recharge = rechargeService.getRechargeDetail(rechargeNo);
            if (recharge != null) {
                return new Result(recharge, CoReturnFormat.SUCCESS);
            } else {
                return new Result(CoReturnFormat.RECHARGE_ORDER_NOT_EXIST);
            }
        } catch (Exception e) {
            log.error("查询充值详情失败，单号：{}", rechargeNo, e);
            return new Result(CoReturnFormat.RECHARGE_DETAIL_FAIL);
        }
    }

    @ApiOperation("取消充值订单")
    @PostMapping("/cancel")
    public Result<String> cancelRechargeOrder(@RequestParam String rechargeNo,
                                             HttpServletRequest request) {
        try {
            //获取当前登录账户
            CereBuyerUser user = (CereBuyerUser) request.getAttribute("user");
            if (BeanUtil.isEmpty(user)) {
                return new Result(CoReturnFormat.USER_NOT_LOGIN);
            }
            
            boolean success = rechargeService.cancelRechargeOrder(rechargeNo, user.getBuyerUserId());
            if (success) {
                return new Result(true, CoReturnFormat.SUCCESS);
            } else {
                return new Result(CoReturnFormat.RECHARGE_CANCEL_FAIL);
            }
        } catch (Exception e) {
            log.error("取消充值订单失败，单号：{}", rechargeNo, e);
            return new Result(CoReturnFormat.RECHARGE_CANCEL_FAIL);
        }
    }

    @ApiOperation("处理充值成功回调")
    @PostMapping("/callback/success")
    public Result<String> handleRechargeSuccess(@RequestParam String rechargeNo,
                                               @RequestParam String thirdPartyOrderNo) {
        try {
            boolean success = rechargeService.handleRechargeSuccess(rechargeNo, thirdPartyOrderNo);
            if (success) {
                return new Result(true, CoReturnFormat.SUCCESS);
            } else {
                return new Result(CoReturnFormat.RECHARGE_CALLBACK_FAIL);
            }
        } catch (Exception e) {
            log.error("处理充值成功回调失败，单号：{}", rechargeNo, e);
            return new Result(CoReturnFormat.RECHARGE_CALLBACK_FAIL);
        }
    }

    @ApiOperation("处理充值失败回调")
    @PostMapping("/callback/fail")
    public Result<String> handleRechargeFail(@RequestParam String rechargeNo,
                                            @RequestParam String failReason) {
        try {
            boolean success = rechargeService.handleRechargeFail(rechargeNo, failReason);
            if (success) {
                return new Result(true, CoReturnFormat.SUCCESS);
            } else {
                return new Result(CoReturnFormat.RECHARGE_CALLBACK_FAIL);
            }
        } catch (Exception e) {
            log.error("处理充值失败回调失败，单号：{}", rechargeNo, e);
            return new Result(CoReturnFormat.RECHARGE_CALLBACK_FAIL);
        }
    }
}
